/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Interface;

import entidades.*;
import Controladores.*;
import Controladores.exceptions.PreexistingEntityException;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author Gatoper
 */
public class JPIPet extends javax.swing.JPanel {

    /**
     * Creates new form JPIPet
     */
    public JPIPet() {
        initComponents();
        this.setSize(new Dimension(300, 400));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        LSpecies = new javax.swing.JLabel();
        TWeight = new javax.swing.JTextField();
        TSpecies = new javax.swing.JTextField();
        Tpicture = new javax.swing.JTextField();
        LAge = new javax.swing.JLabel();
        TAge = new javax.swing.JTextField();
        LWeight = new javax.swing.JLabel();
        BCreate = new javax.swing.JButton();
        TName = new javax.swing.JTextField();
        LName = new javax.swing.JLabel();
        Lpicture = new javax.swing.JLabel();
        LOwner = new javax.swing.JLabel();
        CBOwner = new javax.swing.JComboBox();
        Bfile = new javax.swing.JButton();
        Limg = new javax.swing.JLabel();

        setMaximumSize(new java.awt.Dimension(320, 300));
        setPreferredSize(new java.awt.Dimension(260, 300));

        LSpecies.setText("Species :");

        Snumero(TWeight);

        Sletras(TSpecies);

        Sletras(Tpicture);
        Tpicture.setEnabled(false);

        LAge.setText("Age :");

        Snumero(TAge);

        LWeight.setText("Weight :");

        BCreate.setText("Create");
        BCreate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BCreateActionPerformed(evt);
            }
        });

        Sletras(TName);

        LName.setText("Name :");

        Lpicture.setText("Picture :");

        LOwner.setText("Owner :");

        EntityManagerFactory emf;
        EntityManager em;
        Map<String, String> properties = new HashMap<>();
        emf = Persistence.createEntityManagerFactory("HPVAS");
        em = emf.createEntityManager();
        Owner owner=new Owner();
        OwnerJpaController ojc=new OwnerJpaController(emf);
        List l=ojc.findOwnerEntities();
        String [] aux=new String[l.size()];
        for(int i=0;i<l.size();i++)
        aux[i]=((Owner)l.get(i)).getName();
        CBOwner.setModel(new javax.swing.DefaultComboBoxModel(aux));

        Bfile.setText("Attach");
        Bfile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BfileActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(LOwner)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(CBOwner, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(LName)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(TName))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(LSpecies)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(TSpecies, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(LAge)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(TAge))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(LWeight)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(TWeight)))
                            .addComponent(BCreate))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(Lpicture)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(Tpicture, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(Bfile))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(Limg, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(LName)
                    .addComponent(TName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(LSpecies)
                    .addComponent(TSpecies, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(LAge)
                    .addComponent(TAge, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(LWeight)
                    .addComponent(TWeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Lpicture)
                    .addComponent(Tpicture, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Bfile))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(Limg, javax.swing.GroupLayout.DEFAULT_SIZE, 82, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(LOwner)
                    .addComponent(CBOwner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(BCreate)
                .addGap(22, 22, 22))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void BCreateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BCreateActionPerformed
        // TODO add your handling code here:
        boolean flag = true;
        if (TAge.getText().length() < 1) {
            flag = false;
        }
        if (TName.getText().length() < 1) {
            flag = false;
        }
        if (TSpecies.getText().length() < 1) {
            flag = false;
        }
        if (TWeight.getText().length() < 1) {
            flag = false;
        }
        if (Tpicture.getText().length() < 1) {
            flag = false;
        }
        if (flag) {
            EntityManagerFactory emf;
            EntityManager em;
            Map<String, String> properties = new HashMap<>();
            emf = Persistence.createEntityManagerFactory("HPVAS");
            em = emf.createEntityManager();
            PetJpaController petJpaC = new PetJpaController(emf);
            OwnerJpaController ojc = new OwnerJpaController(emf);
            File file = new File(this.Tpicture.getText());


            //Limg.set
            try {
                FileInputStream fis = new FileInputStream(file);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];

                for (int readNum; (readNum = fis.read(buf)) != -1;) {
                    bos.write(buf, 0, readNum);
                    System.out.println("read " + readNum + " bytes,");
                }
                Pet pet;
                //PetJpaController petJpaC=new PetJpaController();
                String ownid = (String) this.CBOwner.getSelectedItem();
                pet = new Pet(this.TName.getText(), this.TSpecies.getText(), this.TAge.getText(), this.TWeight.getText(), bos.toByteArray(), ojc.findOwner(ownid));
                petJpaC.create(pet);
                JOptionPane.showMessageDialog(this, "Exito");
            } catch (PreexistingEntityException ex) {
                Logger.getLogger(JPIPet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(JPIPet.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            JOptionPane.showMessageDialog(this, "Por favor llene todos los campos");
        }

    }//GEN-LAST:event_BCreateActionPerformed

    private void BfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BfileActionPerformed
        // TODO add your handling code here:
        FileNameExtensionFilter filter = new FileNameExtensionFilter("JPEG file", "jpg", "jpeg");
        JFileChooser chooser = new JFileChooser();
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.setDialogTitle("Choose Image..");
        chooser.setFileFilter(filter);
        chooser.addChoosableFileFilter(filter);
        chooser.showOpenDialog(null);
        File f = chooser.getSelectedFile();
        this.Tpicture.setText(f.getAbsolutePath());
        if (!this.Tpicture.getText().isEmpty()) {
            ImageIcon fot = new ImageIcon(this.Tpicture.getText());
            Icon icono = new ImageIcon(fot.getImage().getScaledInstance(Limg.getWidth(), Limg.getHeight(), Image.SCALE_DEFAULT));
            Limg.setIcon(icono);
            this.repaint();
        }
    }//GEN-LAST:event_BfileActionPerformed
    public void Snumero(JTextField a) {
        a.addKeyListener(new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
                char c = e.getKeyChar();
                if (Character.isLetter(c)) {
                    e.consume();
                }
            }
        });
    }

    public void Sletras(JTextField a) {
        a.addKeyListener(new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
                char c = e.getKeyChar();
                if (Character.isDigit(c)) {
                    e.consume();
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BCreate;
    private javax.swing.JButton Bfile;
    private javax.swing.JComboBox CBOwner;
    private javax.swing.JLabel LAge;
    private javax.swing.JLabel LName;
    private javax.swing.JLabel LOwner;
    private javax.swing.JLabel LSpecies;
    private javax.swing.JLabel LWeight;
    private javax.swing.JLabel Limg;
    private javax.swing.JLabel Lpicture;
    private javax.swing.JTextField TAge;
    private javax.swing.JTextField TName;
    private javax.swing.JTextField TSpecies;
    private javax.swing.JTextField TWeight;
    private javax.swing.JTextField Tpicture;
    // End of variables declaration//GEN-END:variables
}
